package com.woniuxy.goods.controller;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.common.util.CheckTokenUtil;
import com.woniuxy.goods.model.vo.UpdateGoodsVo;
import com.woniuxy.goods.service.GoodsService;
import com.woniuxy.model.entity.Goods;
import com.woniuxy.model.vo.AddGoodsVo;
import com.woniuxy.model.vo.GoodsVo;
import com.woniuxy.response.ResponseResult;
import com.woniuxy.service.FeignUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @Autowired
    HttpServletRequest request;

    private int count=1;

    //可上传文件类型定义
    private List fileTypes = new ArrayList() {
        {
            add("jpg");
            add("png");
        }
    };

    /**
     * 无条件分页查询(只查状态为0的)
     *
     * @return
     */
    @PostMapping("/selectPage")
    public ResponseResult<Page<Goods>> selectPage(@RequestBody GoodsVo goodsVo) {
        return new ResponseResult<>(ResponseResult.SUCCESS, "success", goodsService.selectPage(goodsVo));
    }
    /**
     * 无条件分页查询(只查状态不为1的)
     *
     * @return
     */
    @PostMapping("/selectPage01")
    public ResponseResult<Page<Goods>> selectPage01(@RequestBody GoodsVo goodsVo) {
        log.debug(goodsVo.toString());
        Page<Goods>  page = goodsService.selectPage01(goodsVo);
        return new ResponseResult<>(ResponseResult.SUCCESS, "success",page);
    }
    /**
     * 无条件分页查询(只查状态为3的)
     *
     * @return
     */
    @PostMapping("/selectPage03")
    public ResponseResult<Page<Goods>> selectPage03(@RequestBody GoodsVo goodsVo) {
        return new ResponseResult<>(ResponseResult.SUCCESS, "success", goodsService.selectPage03(goodsVo));
    }

    /**
     * 条件分页查询（状态为0的）
     */
    @PostMapping("/selectPageByCobdition")
    public ResponseResult<Page<Goods>> selectPageByCobdition(@RequestBody GoodsVo goodsVo) {

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.selectPageCondition(goodsVo));
    }

    /**
     * 条件分页查询(不为1的)
     */
    @PostMapping("/selectPageByCobdition01")
    public ResponseResult<Page<Goods>> selectPageByCobdition01(@RequestBody GoodsVo goodsVo) {
        log.debug("条件查询");
        log.debug(goodsVo.toString());
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.selectPageCondition01(goodsVo));

    }

    /**
     * 添加商品
     */
    @PostMapping("/addGoods")
    public ResponseResult<Boolean> addGoods(@RequestBody Goods goods, HttpServletRequest httpServletRequest) {
        String u = httpServletRequest.getHeader("access_token");
        Map<String, Object> user = CheckTokenUtil.getUser(u);
        Integer aid = (Integer) user.get("uid");
        //String account = (String) user.get("account");
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.addGoods(goods,aid));

    }
    /**
     * 根据商品编号集合查询
     */
    @PostMapping("/findByListNumber")
    public ResponseResult<List<Goods>> findByListNumber(@RequestBody List<AddGoodsVo> addGoodsList) {

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.findByListNumber(addGoodsList));
        //return null;
    }

    /**
     * 修改单条数据
     * @param updateGoodsVo
     * @return
     */
    @PostMapping("updateGoods")
    public ResponseResult<Boolean> updateGoods(@RequestBody UpdateGoodsVo updateGoodsVo){
        log.debug("修改" + updateGoodsVo.toString());
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.updateGoods(updateGoodsVo));
    }

    /**
     * 单条信息查询
     */
    @GetMapping("findById/{id}")
    public ResponseResult<Goods> findById(@PathVariable("id") Integer id){

            Goods goods = goodsService.getById(id);

        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goods);
    }

    /**
     * 修改状态为上架“0”
     */
    @GetMapping("updateById/{id}")
    public ResponseResult<Boolean> updateById(@PathVariable("id") Integer id){
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus("0");
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.updateById(goods));
    }
    /**
     * 修改状态为下架“2”
     */
    @GetMapping("updateById01/{id}")
    public ResponseResult<Boolean> updateById01(@PathVariable("id") Integer id){
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus("2");
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.updateById(goods));
    }
    /**
     * 修改状态为删除“1”
     */
    @GetMapping("deleteById/{id}")
    public ResponseResult<Boolean> deleteById(@PathVariable("id") Integer id){
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus("1");
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.updateById(goods));
    }
    /**
     * 修改状态为未上架“2”且添加金额单价
     */
    @GetMapping("pricingById/{id}/{unitPrice}")
    public ResponseResult<Boolean> pricingById(@PathVariable("id") Integer id,@PathVariable("unitPrice") BigDecimal unitPrice){
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus("2");
        goods.setUnitPrice(unitPrice);
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.updateById(goods));
    }

    /**
     * 上传图片
     */
    @RequestMapping("upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpSession session) throws JSONException, IOException {
        JSONObject jsonRsult = new JSONObject();
        if (file.isEmpty()) {
            jsonRsult.put("code", 201);
            jsonRsult.put("msg", "请选择图片");
            return jsonRsult.toString();
        }
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!fileTypes.contains(fileType)) {
            jsonRsult.put("code", 201);
            jsonRsult.put("msg", "仅支持 .png .jpg 图片上传");
            return jsonRsult.toString();
        }
        //获取上传的文件
        log.debug(file.getOriginalFilename());
        String name = file.getOriginalFilename();

        // 重新生成名字，这里是尽量避免文件名不一致
        //substring（）截取字符串方法
        String fileName = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));
        log.debug(fileName);

        // 创建文件对象
        File dest = new File("D:\\images_erp\\" + fileName);

        // 将文件放到指定的位置
        file.transferTo(dest);
        jsonRsult.put("code", 200);
        jsonRsult.put("msg", "上传成功");
        jsonRsult.put("data",fileName);
        return jsonRsult.toString();
    }

    /**
     * 查询所有状态为0的产品编号
     */
    @GetMapping("/findAllGoodsNumber")
    public ResponseResult<List<Goods>> findAllGoodsNumber(){
        return new ResponseResult<>(ResponseResult.SUCCESS,"success",goodsService.findAllGoodsNumber());
    }
}
